<?php

namespace app\common\model\xiluhouse;

use think\Model;

class TaskLog extends Model
{

    // 表名
    protected $name = 'xiluhouse_task_log';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];

    /**
     * 添加数据
     *  @param int    $task_type  1            任务类型:1=每日咨询,2=预约看房,3=浏览房源,4=我要问问,5=分享问问
     */
    public function addtasklog($task_type = 1, $user_id)
    {
        $task_model = new \app\common\model\xiluhouse\Task;
        $task_info = $task_model->where('status', 'normal')->where('type', $task_type)->order(['weigh' => 'desc'])->find();
        if (!$task_info) {
            return false;
        }
        $task_id = $task_info['id'];
        $task_log_model = new \app\common\model\xiluhouse\TaskLog;
        $task_log_data = $task_log_model->where('user_id', $user_id)->where('task_id', $task_id)->whereTime('createtime', 'today')->select();
        if ($task_log_data && count($task_log_data) >= $task_info['limit_num']) {
            return false;
        }
        $saveData['user_id'] = $user_id;
        $saveData['task_id'] = $task_id;
        $saveData['score'] = $task_info['score'];
        $res = $task_log_model->save($saveData);
        if (!$res) {
            return false;
        }
        // 添加积分记录
        User::score($saveData['score'], $user_id, '任务：' . $task_info['name']);
        return true;
    }

    public function task()
    {
        return $this->belongsTo('Task', 'task_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
